<?php
class TempController extends NodeController {
	/**
	 * 模板编辑
	 */
	public function tempList() {
		/* 分页如何缓存 */
		if (isset ( $_GET ['p'] )) {
			$cache_id = $_GET ['p'];
		}
		// 默认设置为15条
		if ($_GET ['num'] > 0) {
			$num = trim ( $_GET ['num'] );
		} else {
			$newNum = require 'config/base.php';
			$num = $newNum ['pagenum'];
		}
		$num = 500;
		// $num = 20;
		// $totalNum = 2000;
		$totalNum = 500;
		$page = $this->page ( $totalNum, $_GET ['p'], $num );
		$this->view ()->assign ( 'num', $page );
		if ($_GET ['type']) {
			$where = array ('type' => $_GET ['type'] );
			$cache_id = $_GET ['type'] . $cache_id;
		}
		$rs = TempModel::instance ()->getTemplateList ( $page ['start'], $page ['num'], 'id,remark,name,action,type,modified', $where );
		$type = TempModel::instance ()->getTemplatesType ();
		$temptype = array ();
		foreach ( $type as $k => $v ) {
			$temptype [$v ['id']] = $v ['name'];
		}
		foreach ( $rs as $k => $v ) {
			$rs [$k] ['type'] = $temptype [$v ['type']];
		}
		// 并且显示历史版本
		$this->view ()->assign ( 'type', $type );
		$this->view ()->assign ( 'typeid', trim ( $_GET ['type'] ) );
		$this->view ()->assign ( 'totalnum', $totalNum );
		$this->view ()->assign ( 'templist', $rs );
		$this->view ()->display ( 'file:news/temp.list.tpl', $cache_id );
	}
	/**
	 * 获取历史版本
	 */
	public function history() {
		if ($_GET ['id'] > 0) {
			$id = $_GET ['id'];
		}
		$rs = TempModel::instance ()->getTempHistory ( array ('temp_id' => $id ), 'id,temp_id,date,remark,action' );
		$this->view ()->assign ( 'templist', $rs );
		$this->view ()->clearCache ( 'file:news/temp.history.tpl' );
		$this->view ()->display ( 'file:news/temp.history.tpl' );
	}
	/**
	 * 从历史模板中获取
	 * Enter description here ...
	 */
	private function getTempFromHistoryById($id) {
		return TempModel::instance ()->getTempHistory ( array ('id' => $id ), 'id,temp_id,date,remark,source,action' );
	}
	/**
	 * 从主模板中获取
	 * Enter description here ...
	 */
	private function getTempFromMainById($id) {
		return TempModel::instance ()->getTemplateById ( $id );
	}
	private function getTempFromMainByName($name) {
		return TempModel::instance ()->getTemplateByName ( $name );
	}
	/**
	 * 
	 * 处理单个模板信息
	 * */
	private function parseTemp($param, $type) {
		switch ($type) {
			case 1 :
				$tempInfo = $this->getTempFromMainByName ( $param );
				break;
			case 2 :
				$tempInfo = $this->getTempFromHistoryById ( $param );
				break;
			default :
				$tempInfo = $this->getTempFromMainById ( $param );
				break;
		}
		//获取最新的更新记录
		if ($type != 2) {
			$history = TempModel::instance ()->getTempHistory ( array ('temp_id' => $tempInfo ['id'] ), 'id,temp_id,date,action', 1 );
		}
		if (! empty ( $history )) {
			$tempInfo = array_merge ( $history [0], $tempInfo );
		}
		if ($type == 2) {
			$tempInfo = $tempInfo [0];
			$tempInfo ['id'] = $tempInfo ['temp_id'];
		}
		// 并且记录日志
		// 修正bug 对$tempInfo 进行匹配
		$tempInfo ['source'] = preg_replace ( "#</textarea>#is", "<\/textarea>", $tempInfo ['source'] );
		$tempInfo ['size'] = $this->filesize ( strlen ( $tempInfo ['source'] ) );
		return $tempInfo;
	}
	/**
	 * 编辑模板 来源历史模板或者主模板
	 */
	public function editTemp() {
		// 从分类编辑进入
		if (isset ( $_GET ['id'] )) {
			$param = $_GET ['id'];
		}
		if ($_GET ['name']) {
			$type = 1;
			$param = $_GET ['name'];
		}
		if ($_GET ['type'] == 'history') {
			$type = 2;
		}
		//这部分代码不应该放在这里
		$tempInfo = $this->parseTemp ( $param, $type );
		$this->view ()->assign ( 'tempinfo', $tempInfo );
		$this->view ()->display ( 'file:news/edit_temp.tpl' );
	}
	/**
	 * 返回kb
	 * @param unknown_type $size
	 */
	private function filesize($size) {
		switch ($size) {
			case $size < 1024 :
				return $size . " Bytes";
				break;
			case $size >= 1024 :
				return round ( $size / 1024, 2 ) . " Kb";
				break;
		}
	}
	/**
	 * 保存分类
	 */
	public function saveTemp() {
		if ($_POST ['id'] > 0) {
			$source = $_POST ['source'];
			$id = $_POST ['id'];
			$user = unserialize ( $_SESSION ['uid'] );
			// 保存历史记录
			$tempInfo = TempModel::instance ()->getTemplateById ( $id );
			$source = preg_replace ( "#<\/textarea>#is", "</textarea>", $source );
			$addTemp = TempModel::instance ()->addTempHistory ( array ('temp_id' => $id, 'source' => addslashes ( $tempInfo ['source'] ), 'date' => time (), 'remark' => $_POST ['remark'], 'action' => $user ['username'] ) );
			if (empty ( $addTemp )) {
				$this->sendNotice ( FAILED );
			}
			// 如果没有开启转义
			if (! get_magic_quotes_gpc ()) {
				$error = TempModel::instance ()->saveTempSource ( addslashes ( $source ), $id );
			} else {
				$error = TempModel::instance ()->saveTempSource ( $source, $id );
			}
			if (! empty ( $error [2] )) {
				$this->sendNotice ( $error [2] );
			}
			//只保留最新10条记录
			$num = TempModel::instance ()->getTempHistory ( array ('temp_id' => $id ), "id" );
			if (count ( $num ) >= 15) {
				asort ( $num );
				TempModel::instance ()->deleteTempHistory ( $id, $num [10] [id] );
			}
			// 添加记录
			TempModel::instance ()->setTempldateStatus ( $id, array ('status' => 0 ) );
			unset ( $_SESSION ['isedit'] );
			// echo '保存成功';
			$this->sendNotice ( SUCCESS, NULL, true );
		}
	}
	/**
	 * 添加模板
	 */
	public function addTemp() {
		// 引入分类
		// $this->view()->assign ( 'category', $this->getCategory () );
		// 检验模板名称是否已经存在
		if (isset ( $_POST ) && ! empty ( $_POST ['name'] )) {
			$flag = TempModel::instance ()->getTemplateByName ( trim ( $_POST ['name'] ) );
			if (! empty ( $flag )) {
				$this->sendNotice ( 'temp name already exist', NULL, FALSE );
			}
			$result = TempModel::instance ()->addTemp ( array ('name' => trim ( $_POST ['name'] ), 'remark' => $_POST ['remark'], 'type' => $_POST ['type'] ) );
			$this->sendNotice ( self::SUCEESS, NULL, TRUE );
		} else {
			$this->sendNotice ( '模板已经存在', NULL, false );
		}
		$this->view ()->clearCache ( 'file:news/addtemp.tpl' );
		$this->view ()->display ( 'file:news/addtemp.tpl' );
	}
	/**
	 * 分页
	 *
	 * @return void
	 */
	protected function page($total, $pageid, $num) {
		$pageid = isset ( $pageid ) ? $pageid : 1;
		$rs = $pageid * $num - $total;
		$start = ($pageid - 1) * $num;
		$pagenum = ceil ( $total / $num );
		/*修正分类不包含内容 显示404错误*/
		$pagenum = $pagenum == 0 ? 1 : $pagenum;
		/*如果超过了分类页数 404错误*/
		
		if ($pageid > $pagenum) {
			//echo FAILED . 'The paging number out of range';
			return false;
		
		//  exit();
		// header("HTTP/1.1 404 Not Found");
		}
		
		$page = array ('start' => $start, 'num' => $num, 'current' => $pageid, 'page' => $pagenum );
		return $page;
	}
}